package com.demo.gateway.rest;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

/**
 *
 * @author: demo
 * @date: 2020年6月23日
 * @Description : RestHttpUtils
 * 
 */
@Component
public class RestHttpUtils {

	@Autowired
	private RestTemplate restTemplate;
	private static RestTemplate httpRest;

	@PostConstruct
	public void init() {
		httpRest = restTemplate;
	}
    /**
     * get请求  
     * @param url
     * @return
     */
	public static String doGet(String url) {
		ResponseEntity<String> result = httpRest.getForEntity(url, String.class);
		return result.getBody();
	}
     /**
      * post请求
      * @param url
      * @param json
      * @return
      */
	public static String doPost(String url, JSONObject json) {
		return doPost(url, json.toJSONString());
	}

	public static String doPost(String url, String json) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
		ResponseEntity<String> result = httpRest.postForEntity(url, httpEntity, String.class);
		return result.getBody();
	}
    /**
     * post form请求
     * @param url
     * @param bodys
     * @param headers
     * @return
     */
	public static String doPostForm(String url, Map<String, Object> params, Map<String, Object> headers) {
		HttpHeaders httpHeaders = new HttpHeaders();
		headers.forEach((key, value) -> {
			httpHeaders.add(key, value.toString());
		});
		MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<String, Object>();
		params.forEach((key, value) -> {
			multiValueMap.add(key, value);
		});
		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, httpHeaders);
		ResponseEntity<String> result = httpRest.postForEntity(url, httpEntity, String.class);
		return result.getBody();
	}

}
